/*
 * Title:        CloudScheduler Toolkit
 * Description:  a Toolkit for Modeling and Simulation of Job Scheduling and Resource Provisioning in Cloud System
 * Licence:      GPL - http://www.gnu.org/copyleft/gpl.html
 * Author:       Fuhui Wu
 *
 * Copyright (c) 2013-2014, The National University of Defense Technology, China
 */

package org.nudt.jCloud.simulation;

import java.util.ArrayList;
import java.util.List;

import org.nudt.jCloud.resourceManager.ResManager;
import org.nudt.jCloud.util.Log;

public class CloudInfoService extends SimEntity{
	private List<UserBroker> userBrokerList;
	private List<ResManager> rMs;
	
	public CloudInfoService(String name) {
		super(name);
		userBrokerList = new ArrayList<UserBroker>();
		rMs = new ArrayList<ResManager>();
	}
	
	public void reset(){
		for(int i=0; i<userBrokerList.size(); ++i){
			userBrokerList.get(i).reset();
		}
		for(int i=0; i<rMs.size(); ++i){
			rMs.get(i).reset();
		}
	}
	
	public void userRegister(UserBroker user){
		userBrokerList.add(user);
	}
	
	public void resManagerRegister(ResManager rM){
		getRMs().add(rM);
	}
	
	@Override
	public void startEntity() {
		
	}

	@Override
	public void processEvent(SimEvent event) {
		switch(event.getTag()){
			case SIMTag.REGISTER_RESOURCE:
				Log.println("CIS received a resource manager register of id: "+event.getSrc());
				resManagerRegister((ResManager)CloudSchedSIM.getEntities().get(event.getSrc()));
				break;
			case SIMTag.REGISTER_USERBROKER:
				Log.println("CIS received a user broker register of id: "+event.getSrc());
				UserBroker user = (UserBroker)CloudSchedSIM.getEntities().get(event.getSrc());
				userRegister(user);
				/**
				 * select a resource manager for current user.
				 */
				ResManager rm = rMs.get(0);
				for(int i=1; i<rMs.size(); ++i){
					if(rMs.get(i).getFrwkList().size()<rm.getFrwkList().size()){
						rm = rMs.get(i);
					}
				}
				/**
				 * register the framework to the selected resource manager.
				 */
				rm.registerFrwk(user.getFrwk());
				sendNow(event.getSrc(), SIMTag.REGISTER_USERBROKER_ACK, rm);
				break;
		}
	}

	public List<ResManager> getRMs() {
		return rMs;
	}

	public void setRMs(List<ResManager> rMs) {
		this.rMs = rMs;
	}

	public List<UserBroker> getUserBrokerList() {
		return userBrokerList;
	}

	public void setUserBrokerList(List<UserBroker> userBrokerList) {
		this.userBrokerList = userBrokerList;
	}	

}
